import { Button, ConfigProvider, Form, Input, message, Pagination, Popconfirm, Table, type FormProps, type PaginationProps, type TableColumnsType } from "antd";
import '../../assets/css/Building/buildingCss.less'
import type { TableRowSelection } from "antd/es/table/interface";
import zhCN from 'antd/locale/zh_CN';
import { useEffect, useState } from "react";
import { AdministratorList, deleteAdministrator } from "../../apis/Administrator";
import type { AdministratorListFaceList, AdministratorListParams, editFace } from "../../type/Administrator";
import DiaLog from "../../component/Administrator/DiaLog";

type FieldType = {
    key: string
};
interface DataType {
    key: React.Key;
    id: number;
    username: string;
    pass: string;
    name: string;
    tel: string;
    typeid: number;
    typeName: string;
    verifyCode?: any;
    token?: any;
}
export default function Administrator() {
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [params, setParams] = useState<AdministratorListParams>({ page: 1, psize: 10, type: 0 })
    const [ListData, setListData] = useState<AdministratorListFaceList[]>()
    const [total, setTotal] = useState<number>()
    const [openAdd, setOpenAdd] = useState(false)
    const [editContent, setEditContent] = useState<editFace>({id:0});
    useEffect(() => {
        // 请求数据
        GetData()
    }, [])
    const GetData = async () => {
        let res = await AdministratorList(params)
        setListData(res.data.list)
        setTotal(res.data.counts)
    }
    const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
        setParams({ ...params, key: values.key })
    };
    useEffect(() => {
        GetData()
    }, [params])
    // 关闭弹窗
    const refresh = () => {
        setOpenAdd(false)
        setEditContent({...editContent, id: 0})
        GetData()
    }
    // 删除数据
    const del = async (id: number) => {
        let res = await deleteAdministrator(id)
        if (res.errCode == 10000) {
            message.success('删除成功')
            GetData()
        } else {
            message.error('删除失败')
        }
    }
    const columns: TableColumnsType<DataType> = [
        { title: 'id', dataIndex: 'id', width: 100, align: 'center' },
        { title: '登录账号', dataIndex: 'username', align: 'center' },
        { title: '姓名', dataIndex: 'name', align: 'center' },
        { title: '手机号', dataIndex: 'tel', align: 'center' },
        { title: '类型', dataIndex: 'typeName', align: 'center' },
        {
            title: '操作', dataIndex: 'address', width: 300, align: 'center',
            render: (_, record) => (
                <div style={{ display: 'flex', justifyContent: 'center' }}>-
                    {/* 你可以在这里添加实际的操作按钮 */}
                    <Button variant="solid" color="green" onClick={()=>{
                        setOpenAdd(true)
                        setEditContent({...editContent,id:record.id,data:record})
                    }} type="primary">修改</Button>
                    <Popconfirm
                        title="提示"
                        description="你确定要删除这条数据吗?"
                        onConfirm={() => { del(Number(record.id)) }}
                        okText="删除"
                        cancelText="取消"
                    >
                        <Button variant="solid" color="red" style={{ marginLeft: '10px' }} type="primary">删除</Button>
                    </Popconfirm>
                </div>
            )
        },
    ];

    const dataSource: DataType[] | undefined = ListData?.map((item) => ({
        key: item.id, // Table组件需要唯一的key
        id: item.id,
        username: item.username,
        pass: item.pass,
        name: item.name,
        tel: item.tel,
        typeid: item.typeid,
        typeName: item.typeName,
        verifyCode: item.verifyCode,
        token: item.token,
    }));
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection: TableRowSelection<DataType> = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    // 修改分页
    const onShowSizeChange: PaginationProps['onShowSizeChange'] = (current, pageSize) => {
        setParams({ ...params, page: current, psize: pageSize });
    };

    const onChange: PaginationProps['onChange'] = (page, pageSize) => {
        setParams({
            ...params,
            page: page,
            psize: pageSize || params.psize
        });
    };

    return (
        <>
            <ConfigProvider locale={zhCN}>
                <div className='ContentBody'>
                    <div className="header">
                        <p>管理员列表</p>
                    </div>
                    <div className="search">
                        <Form
                            name="basic"
                            layout="inline"
                            initialValues={{ remember: true }}
                            onFinish={onFinish}
                            autoComplete="off"
                        >
                            <Form.Item<FieldType>
                                label="关键字"
                                name="key"
                            >
                                <Input placeholder="关键字" />
                            </Form.Item>
                            <Form.Item label={null}>
                                <Button type="primary" htmlType="submit">
                                    查询
                                </Button>
                            </Form.Item>
                        </Form>
                    </div>
                    <div className='AddBtn'>
                        <Button variant="solid" onClick={()=>setOpenAdd(true)} type="primary">添加</Button>
                    </div>
                    <Table<DataType> rowSelection={rowSelection} columns={columns} dataSource={dataSource}
                        scroll={{ x: 'max-content' }}
                        tableLayout="auto"
                        style={{ width: '100%' }}
                        pagination={false} // 取消分页
                    />
                    <Pagination
                        showSizeChanger
                        onShowSizeChange={onShowSizeChange}
                        onChange={onChange}
                        current={params.page}
                        pageSize={params.psize}
                        total={total}
                        showTotal={(total) => `共 ${total} 条记录`}
                        showQuickJumper
                    />
                    {/* 添加和修改 */}
                    <DiaLog openAdd={openAdd} refresh={refresh} editContent={editContent} />
                </div>
            </ConfigProvider>
        </>
    )
}